package com.lancea12.buster.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class RobotEndpoint implements Runnable {

	private Socket endpoint;
	private boolean valid;
	private InputStream in;
	private Handler textHandler;
	private Handler responseHandler;
	private RobotMessageHandler arduinoHandler;
	
	RobotEndpoint(Socket endpoint, Handler textHandler, 
			Handler responseHandler,
			RobotMessageHandler arduinoHandler,
			boolean valid){
		this.textHandler = textHandler;
		this.responseHandler = responseHandler;
		this.arduinoHandler = arduinoHandler;
		this.endpoint = endpoint;
		this.valid = valid;
	}
	
	@Override
	public void run() {
		
		Log.d("Buster", "started new robot socket thread");

		if(!valid){
			try {
				endpoint.getOutputStream().write("robot already has controller".getBytes());
				endpoint.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			in = endpoint.getInputStream();
			while(endpoint.isConnected() && !endpoint.isClosed()){
				if(in.available() > 0){
					processRequest();
				}
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
		        Message mes = new Message();
		        Bundle bun = new Bundle();
		        bun.putString("socket", "connected");
		        mes.setData(bun);
				responseHandler.sendMessage(mes);
			}
			
			Log.d("Buster", "robot socket got disconnected");
			// send a message that the controller is no longer connected
	        Message mes = new Message();
	        Bundle bun = new Bundle();
	        bun.putString("socket", "disconnected");
	        mes.setData(bun);
			responseHandler.sendMessage(mes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	void processRequest() throws IOException{
		byte buf[] = new byte[in.available()];
		in.read(buf);
		Log.d("receive", new String(buf));
		
        Message mes = new Message();
        Bundle bun = new Bundle();
        bun.putString("response", new String(buf));
        mes.setData(bun);
		//textHandler.sendMessage(mes);
		arduinoHandler.sendMessage(mes);
/*		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
*/
	}
}
